package cn.wolfcode.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.concurrent.Callable;

@Controller
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/updatePwd")
    public String updatePwd(){
        return "/person/updatePwd";
    }

    @RequestMapping("/updatePassword")
    @ResponseBody
    public JsonResult updatePassword(String newPassword, String oldPassword, HttpSession session){
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipal();
        //Employee employee = (Employee)session.getAttribute("EMPLOYEE_IN_SESSION");
        try {
            //如果和原密码相同,就执行
            employeeService.updatePwd(employee,oldPassword,newPassword);
            session.invalidate();
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"原密码错误");
        }
    }

    //重置
    @RequestMapping("/resetPwd")
    public String resetPwd(Model model,Long id,HttpSession session){
        //要修改的员工
        Employee employee = employeeService.get(id);
        session.setAttribute("EMPLOYEERESET_IN_SESSION",employee);
        model.addAttribute("employee",employee);
        return "/person/resetPwd";
    }

    //重置密码
    @RequestMapping("/resetPassword")
    @ResponseBody
    public JsonResult resetPassword(String newPassword, HttpSession session){
        //拿到要修改的员工
        Employee employee = (Employee)session.getAttribute("EMPLOYEERESET_IN_SESSION");
        try {
            //如果和原密码相同,就执行
            employeeService.resetPwd(employee, newPassword);
            session.invalidate();
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"重置异常");
        }
    }
}
